#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "cJSON.h"

#define PORT 8080
#define BACKLOG 5
#define BUFFER_SIZE 1024

// 共享内存相关变量
int shmid;
char *shmaddr;

// 线程函数，用于将数据写入共享内存
void *write_to_shm(void *arg) {
    char *data = (char *)arg;

    // 连接到共享内存
    shmaddr = shmat(shmid, NULL, 0);
    if (shmaddr == (void *)-1) {
        perror("shmat");
        pthread_exit(NULL);
    }

    // 将数据写入共享内存
    strncpy(shmaddr, data, BUFFER_SIZE);

    // 断开共享内存连接
    shmdt(shmaddr);

    pthread_exit(NULL);
}

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[BUFFER_SIZE] = {0};
    pthread_t thread;
    cJSON *temp,*hum,*lht,*mode;
    // 创建共享内存
    shmid = shmget(0x005, BUFFER_SIZE, IPC_CREAT | 0777);
    if (shmid < 0) {
        perror("shmget");
        exit(EXIT_FAILURE);
    }
    printf("共享内存创建成功\n");

    // 创建 socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 限制地址重用
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

    // 配置服务器地址结构
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY; // 监听所有接口
    address.sin_port = htons(PORT); // 指定端口

    // 设置IP地址
    const char *ip_address = "192.169.2.197";
    inet_pton(AF_INET, ip_address, &(address.sin_addr));

    // 绑定 socket
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 开始监听
    if (listen(server_fd, BACKLOG) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    printf("TCP server is listening on port %d\n", PORT);

    while (1) {
        // 接受客户端连接
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
            perror("accept");
            exit(EXIT_FAILURE);
        }

        printf("New connection accepted\n");

        // 读取数据
        int valread = read(new_socket, buffer, BUFFER_SIZE);

        // 解析 JSON 字符串
        cJSON *json = cJSON_Parse(buffer);
        if (json == NULL) {
            printf("JSON parsing error\n");
            close(new_socket);
            continue;
        }

    if(json)	
    {
        char * root = cJSON_Print(json);
        if(root)
        {
            printf("%s\n",root);
            free (root);
        }
    }	

        // 获取 data 数组
        //cJSON *data_array = cJSON_GetObjectItem(json, "data");
        
	/*if (data_array == NULL) {
            printf("Invalid data format\n");
            cJSON_Delete(json);
            close(new_socket);
            continue;
        }*/
	/*
        // 遍历数组并打印内容
        for (int i = 0; i < cJSON_GetArraySize(data_array); i++) {
            cJSON *item = cJSON_GetArrayItem(data_array, i);
            int key = cJSON_GetObjectItem(item, "key")->valueint;
            const char *name = cJSON_GetObjectItem(item, "name")->valuestring;
            double data_value = cJSON_GetObjectItem(item, "data")->valuedouble;

            printf("Key: %d, Name: %s, Data: %.2f\n", key, name, data_value);
        }*/

        // 释放 JSON 对象
        cJSON_Delete(json);

        // 创建线程将数据写入共享内存
        if (pthread_create(&thread, NULL, write_to_shm, (void *)buffer) != 0) {
            perror("pthread_create");
            close(new_socket);
            continue;
        }

        // 发送回应
        const char *message = "Hello from server";
        send(new_socket, message, strlen(message), 0);
        printf("Message sent\n");

        // 关闭连接
        close(new_socket);

        // 等待线程结束
        pthread_join(thread, NULL);
    }

    // 删除共享内存
    shmctl(shmid, IPC_RMID, NULL);

    return 0;
}

